package com.hp.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class MatrixParamConverter {
    /**
     * 列优先转行优先矩阵转换
     *
     * @param items 列优先排序的原始数据
     * @param rows  目标矩阵行数
     * @param cols  目标矩阵列数
     * @return 重构后的行优先矩阵
     * @throws IllegalArgumentException 当元素总数超过rows*cols时抛出异常
     */
    public static List<List<String>> convert(List<String> items, int rows, int cols) {
        if (items.size() > rows * cols) {
            throw new IllegalArgumentException("元素总数必须小于等于rows*cols");
        }

        List<List<String>> matrix = new ArrayList<>(rows);
        for (int r = 0; r < rows; r++) {
            List<String> row = new ArrayList<>(cols);
            for (int c = 0; c < cols; c++) {
                int index = c * rows + r;
                row.add(index < items.size() ? items.get(index) : null);
            }
            matrix.add(row);
        }
        return matrix;
    }


    /**
     * 列优先转行优先矩阵转换
     *
     * @param items 列优先排序的原始数据
     * @param rows  目标矩阵行数
     * @param cols  目标矩阵列数
     * @return 重构后的行优先矩阵
     * @throws IllegalArgumentException 当元素总数超过rows*cols时抛出异常
     */
    public static List<List<String>> convertStream(List<String> items, int rows, int cols) {
        if (items.size() > rows * cols) {
            throw new IllegalArgumentException("元素总数必须小于等于rows*cols");
        }

        return IntStream.range(0, rows)
                .mapToObj(r -> IntStream.range(0, cols)
                        .mapToObj(c -> {
                            int index = c * rows + r;
                            return index < items.size() ? items.get(index) : null;
                        })
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());
    }


    public static void main(String[] args) {

//        List<String> sample = Arrays.asList("物品1", "物品4", "物品7", "物品2", "物品5", "物品8", "物品3", "物品6", "物品9");
        List<String> sample = Arrays.asList("A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3");
        var lists = convert(sample, 3, 4);
        lists.forEach(System.out::println);
        System.out.println("-------------------------------------------");
        List<String> yoloResult1 = Arrays.asList("A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3", "C4");
        List<List<String>> lists1 = convertStream(yoloResult1, 3, 4);
        lists1.forEach(System.out::println);

        System.out.println("-------------------------------------------");
        List<String> yoloResult2 = Arrays.asList("A1", "A2", "A3", "A4", "B1", "B2", "B3", "B4", "C1", "C2", "C3");
        List<List<String>> lists2 = convertStream(yoloResult2, 3, 4);
        lists2.forEach(System.out::println);
    }


}
